@icon("res://GDBase/Icons/cells.svg")
@tool
extends Node2D
class_name CellsProgressBar
##这是一个简单的格子进度条组件脚本。您可以将场景作为该进度条组件的格子。
##因为您可对该进度条的格子进行高度自定义。

@export_group("格子场景")
@export var cell_scene:PackedScene
@export var cell_size_x:int = 2
@export var cell_size_y:int = 3
@export_group("格子数量")
@export var max_cells_num:int:
	set(new_num):
		max_cells_num = new_num
		current_cells_num = current_cells_num
@export var current_cells_num:int:
	set(new_num):
		new_num = clamp(new_num,0,max_cells_num)
		if current_cells_num == new_num:
			return
		elif current_cells_num > new_num:
			_recycle_cells(current_cells_num - new_num)
			current_cells_num = new_num
		else :
			_spawner_cells(new_num - current_cells_num)
		current_cells_num = new_num
@export var vertical:bool:
	set(value):
		vertical = value
		_reset_cell_rotation_degrees()


var cells:Array[Sprite2D]
var cell_spawner:Spawner

func _reset_cell_rotation_degrees():
	if vertical:
		rotation_degrees = 90
	else:
		rotation_degrees = 0

func _change_cell_num(new_num:int):
	current_cells_num = new_num

func _spawner_cells(num:int):
	_create_cell_spawner()
	for i in num:
		var cell:Sprite2D = cell_spawner.request_instance()
		cells.append(cell)
		cell.position.y = -(cells.size() - 1) * cell_size_y
		add_child(cell)

func _recycle_cells(num:int):
	_create_cell_spawner()
	for i in num:
		var cell = cells.pop_back()
		cell_spawner.recycle_instance(cell)

func _create_cell_spawner():
	if !cell_spawner:
		cell_spawner = Spawner.new()
		cell_spawner.init(cell_scene)
